from django.shortcuts import render

# Create your views here.


from django.shortcuts import render, HttpResponse
import random
from utils.tencent.sms import send_sms_single
from django.conf import settings
from app01.models import UserInfo
from django import forms
from django.core.validators import RegexValidator
from django.core.exceptions import ValidationError
import redis
import hashlib
def send_sms(request):
    """ 发送短信
        ?tpl=login  -> 548762
        ?tpl=register -> 548760
    """
    phone = request.POST.get('phone')
    tpl = request.GET.get('tpl')
    template_id = settings.TENCENT_SMS_TEMPLATE.get(tpl)
    if not template_id:
        return HttpResponse('模板不存在')

    code = random.randrange(1000, 9999)
    res = send_sms_single(phone, template_id, [code,5])
    if res['result'] == 0:
        conn = redis.Redis(host='192.168.0.106', port=6379, password='foobared', encoding='utf-8')
        conn.set(phone, code, ex=60*20)
        return HttpResponse('验证码发送成功')

    else:
        return HttpResponse(res['errmsg'])


# param template_param_list: 短信模板所需参数列表，例如:【验证码：{1}，描述：{2}】，则传递参数 [888,666]按顺序去格式化模板

class RegisterModelForm(forms.ModelForm):
    phone = forms.CharField(label='手机号',validators=[RegexValidator(r'^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|166|198|199|(147))\\d{8}$', '手机号格式错误')]),
    password = forms.CharField(label='密码',widget=forms.PasswordInput())
    passwords = forms.CharField(label='确认密码',widget=forms.PasswordInput())
    code = forms.CharField(label='验证码',widget=forms.TextInput)

    class Meta:
        model = UserInfo
        fields = ['username', 'email', 'password', 'passwords', 'phone', 'code']

    def __init__(self,*args,**kwargs):
        super().__init__(*args,**kwargs)
        for name,field in self.fields.items():
            field.widget.attrs['class'] = 'form-control'
            field.widget.attrs['name'] = name
            field.widget.attrs['placeholder'] = f'请输入{field.label}'

    def clean(self):
        self._validate_unique = True    # 校验数据库唯一性
        password = self.cleaned_data.get('password','')
        passwords = self.cleaned_data.get('passwords',)
        print(4)
        if password == passwords:
            md5 = hashlib.md5()
            md5.update(password.encode('utf-8'))
            self.cleaned_data['password'] = md5.hexdigest()
            conn = redis.Redis(host='192.168.0.106', port=6379, password='foobared', encoding='utf-8')
            phone = self.cleaned_data.get('phone', )
            code = self.cleaned_data.get('code', '')
            r_code = conn.get(phone)
            if int(code) == int(r_code):
                return self.cleaned_data
            self.add_error('code','验证码错误')
            # return ValidationError('验证码错误')
        self.add_error('passwords','密码不一致')
        # return ValidationError('密码不一致')


def register(request):
    form = RegisterModelForm()
    if request.method == 'POST':
        form = RegisterModelForm(request.POST)
        if form.is_valid():
            form.save()
            print(form.cleaned_data)
            return HttpResponse('注册成功')
    return render(request,'register.html',{'form':form})

